package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.qiniu.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/*
    ヾ(❀ﾟ▽ﾟ)ノ 
 
 Grey1996year@163.com 
 
*/
@RestController
@RequestMapping("/member")
public class MemberController {
	@Autowired
	private JedisPool jedisPool;

	@Reference
	private MemberService memberService;

	@RequestMapping("/login")
	public Result login(@RequestBody Map map, HttpServletResponse response){
		//获取jedis中存储的login验证码
		String telephone = (String) map.get("telephone");
		String validateCode_redis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
		//获取用户输入的验证码
		String validateCode_Input = (String) map.get("validateCode");
		//判断
		if (validateCode_redis==null || !validateCode_redis.equals(validateCode_Input)) {
			return new Result(false, MessageConstant.VALIDATECODE_ERROR);
		}

		//用户输入正确
		//调用业务方法进行处理
		//1.先根据手机号查询该用户是不是会员
		Member member = memberService.queryIsMember(telephone);
		//不是会员
		if (member==null){
			//自动注册
			member = new Member();
			member.setPhoneNumber(telephone);
			member.setRegTime(new Date());
			memberService.addMember(member);
		}

		//登陆成功
		//向客户端写入cookie,有效期30天
		Cookie cookie = new Cookie("login_telephone",telephone);
		cookie.setMaxAge(60*60*24*30);
		response.addCookie(cookie);

		//将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟
		String member_Info = JSON.toJSON(member).toString();
		jedisPool.getResource().setex(telephone,60*30,member_Info);
		return new Result(true,MessageConstant.LOGIN_SUCCESS);
	}

}
